package com.lin.interceptor;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.lin.constant.UserConstants;
import com.lin.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 从session获取请求头中的token
        String token = (String) request.getSession().getAttribute(UserConstants.JWT_HEADER_INFO);
        System.out.println("token:" + token);

        // 去除token前缀, 如果不是Bearer开头, 则返回null
        if (token != null && token.startsWith("Bearer "))
            token = token.substring(7);
        else
            token = null;
        try{
            if (token == null)
                throw new RuntimeException("token丢失");
            JWTUtil.verify(token); // 验证令牌
            return true; // 放行
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "签名不匹配");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token已过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "算法不匹配");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token失效");
        }
        map.put("state", false); // 设置状态码
        String jsonStr = JSONUtil.toJsonStr(map);
        response.setContentType("application/json;charset=UTF-8");
        // 将响应数据写入响应体中
        response.getWriter().println(jsonStr);
        return false;
    }
}
